"""
Redistribution and use in source and binary forms, with or
without modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
  list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
  notice, this list of conditions and the following disclaimer
  in the documentation and/or other materials provided with the distribution.
* Neither the names of the authers, nor the names of its contributors, may be used to endorse or 
  promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS/COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND 
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 
REGENTS/COPYRIGHT OWNERS AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF 
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

@Author Fredrique Samuels <fredriquesamuels@gmail.com>
@threadbase.py
"""

from thread import start_new_thread
import time


#===============================================#

class pytATerminate:
    """ Class defining termination requets """

    def __init__(self):
        """ Class Constructor """
        self._terminate = False

    def terminate(self):
        """ Requests the thread to exit """
        self._terminate = True

    def testTerminate(self):
        """ Tell is the thread has been requested to
        terminate

        @return True if a call to self.terminate() has been called """
        return self._terminate

    def resetTerminate(self):
        """ Reset the termination flag to False """
        self._terminate = False
    
#===============================================#

class pytThread(pytATerminate):
    """ Class for running and sstopping threads """
    
    def __init__(self):
        """ Class constructor
        @param runner An instance of IThread"""
        pytATerminate.__init__(self)
        self.__isRunning = False
        

    def isRunning(self):
        """ Return true if the thread is still running
        
        @return Running status """
        return self.__isRunning

    def start(self,args = None):
        """ Start the thread.
        This methods will through an exception if
        isRunning() returns True.

        @param args: Optional parameters to pass to IThread.run()
        """
        
        if self.isRunning():
            raise Exception("Thread has already started!!!!")
       
        start_new_thread(self.__main_loop,(args,))

    def __main_loop(self,args):
        """ Thread main loop """
        self.__isRunning = True
        try:
            self.main_loop(args)
        except Exception,e:
            print e
        self.__isRunning = False
        self.resetTerminate()
        
    def main_loop(self,args):
        """ Main function where all the good things happen :)
        @note: This method must be reimplemented. Make sure 
        you use self.testTerminate() to test for exit flag.
        
        example:
        
            while not self.testTerminate():
                do stuff"""
        raise Exception("pytThread.main_loop(self,args) must be reimplmented")
        

#========================================================#
#
#class testRunner(pytThread):
#    def __init__(self):
#        """ Class Constructor """
#        pytThread.__init__(self)
#        
#    def main_loop(self,args):
#        while not self.testTerminate():
#            print 'running'
#            time.sleep(1)
#        print "exiting"
#
##==========================================================#
#        
#if __name__ == '__main__':
#    t = testRunner()
#    t.start()
#    time.sleep(2)
#    t.terminate()
#    time.sleep(4)
#    
    
